import React, { useState, Fragment } from 'react';
import {
    Form, Image, message,
    Button, Row, Col, Input,
    Select, Table, Cascader,
    Badge, Modal
} from 'antd';
import {
    PlusOutlined,
    ExclamationCircleOutlined
} from '@ant-design/icons';
import Head from 'next/head';
import Router from 'next/router';
import AdvancedSearchForm from '@/components/Form'

const columns = (props) => {
    const { userinfo } = props.state
    return [
        {
            title: '用户头像',
            dataIndex: 'avatar',
            align: 'center',
            key: 'avatar',
            width: 70,
            rowKey: record => record.dataIndex,
            render: avatar => <a><Image src={avatar} preview={{src: avatar}} /></a>,
        },
        {
            title: '会员名称',
            dataIndex: 'username',
            align: 'center',
            key: 'username',
            width: 150,
            rowKey: record => record.dataIndex,
            render: (text, record) => <a>{text + (record.administrator && record.id === userinfo.id ? '(管理员)' : '')}</a>,
        },
        {
            title: '账号状态',
            align: 'center',
            dataIndex: 'status',
            key: 'status',
            width: 150,
            rowKey: record => record.dataIndex,
            render: status =>
                <span>
                    <Badge status={status === 1001 ? 'success' : 'default'} />
                    {status === 1001 ? '启用' : '禁用'}
                </span>,
        },
        {
            title: '电子邮箱',
            align: 'center',
            dataIndex: 'email',
            key: 'email',
            width: 150,
            rowKey: record => record.dataIndex
        },
        {
            title: '创建时间',
            align: 'center',
            dataIndex: 'createTime',
            key: 'createTime',
            width: 150,
            rowKey: record => record.dataIndex,
            render: time => React.$filters.timeFilter(new Date(time).getTime())
        },
        {
            title: '修改时间',
            align: 'center',
            dataIndex: 'updateTime',
            key: 'updateTime',
            width: 150,
            rowKey: record => record.dataIndex,
            render: time => React.$filters.timeFilter(new Date(time).getTime())
        },
        {
            title: '操作',
            align: 'center',
            key: 'action',
            width: 180,
            rowKey: record => record.dataIndex,
            render: (text, record) => (
                <div>
                    <a style={{ marginRight: 16 }} onClick={() => Router.push(`/user/view?id=${record.id}`)}>查看</a>
                    {userinfo.administrator && userinfo.id !== record.id && <a style={{ marginRight: 16 }} onClick={() => props.handleChangeStatus(record)}>{record.status && record.status === 1002 ? '启用' : '禁用'}</a>}
                    {userinfo.administrator && <a style={{ marginRight: 16 }} onClick={() => Router.push(`/user/edit?id=${record.id}`)}>编辑</a>}
                    {userinfo.administrator && userinfo.id !== record.id && <a style={{ marginRight: 16 }} onClick={() => props.handleDelete(record)}>删除</a>}
                </div>
            ),
        },
    ];
}
function handleChange (value) {
    console.log(`selected ${value}`);
}
class User extends React.Component {
    constructor(props) {
        super(props)
    }
    static async getInitialProps ({ $api, $filters, userinfo }) {
        // 从query参数中回去id
        //通过process的browser属性判断处于何种环境：Node环境下为false,浏览器为true
        // 发送服务器请求
        // let token = Base64.decode(req.headers[''])
        const res = await $api.user.get()
        if (res && res.success) {
            return {
                loading: false,
                data: res.data[0],
                pageData: {
                    current: 1,
                    pageSize: 10,
                    total: res.data[1],
                    pageSizeOptions: [5, 10, 20, 50]
                },
                $filters,
                userinfo
            }
        } else {
            return {
                loading: true,
                data: [],
                pageData: {
                    current: 1,
                    pageSize: 10,
                    total: 999,
                    pageSizeOptions: [5, 10, 20, 50]
                },
                $filters,
                userinfo
            }
        }
    }
    state = {
        queryData: {},
        hasData: true,
        formItems: [
            {
                label: '会员名称',
                type: 1,
                name: 'username',
                placeholder: '会员名称'
            },
            {
                label: '状态',
                type: 2,
                name: 'status',
                placeholder: '状态',
                fieldNames: {
                    label: 'description',
                    value: 'code'
                },
                options: [{
                    code: '',
                    description: '全部'
                }, {
                    code: 1001,
                    description: '已启用'
                }, {
                    code: 1002,
                    description: '已停用'
                }]
            },
            {
                label: '邮箱',
                type: 1,
                name: 'email',
                placeholder: '邮箱'
            }
        ],
        scroll: {
            y: 400
        },
        ...this.props
    }
    async handlerFormSubmit (values, isPage) {
        isPage && this.setState({ loading: true, pageData: values })
        !isPage && this.setState({
            loading: true,
            queryData: values,
            pageData: {
                current: 1,
                pageSize: 10,
                total: this.state.pageData.total,
                pageSizeOptions: [5, 10, 20, 50]
            }
        })
        // 发送服务器请求
        const { current, pageSize } = isPage ? values : this.state.pageData
        const params = { current, pageSize, ...this.state.queryData }
        const res = await $api.user.get(params)
        if (res && res.success) {
            this.setState({
                loading: false,
                data: res.data[0],
                pageData: {
                    current,
                    pageSize,
                    total: res.data[1]
                }
            })
        } else {
            this.setState({
                loading: false,
                data: [],
                pageData: {
                    current,
                    pageSize,
                    total: 0,
                }
            })
        }
    }
    async handleChangeStatus (item) {
        let { id, status } = item
        status = status === 1001 ? 1002 : 1001
        console.log(this.props, ' $api')
        const res = await $api.user.status({ id, status })
        if (res && res.success) {
            message.success(res.message)
            this.setState({ reset: true })
            this.handlerFormSubmit({ ...this.state.pageData, status: '' }, true)
            return
        }
        message.error(res.message)
    }
    async handleDelete (item) {
        Modal.confirm({
            title: '温馨提示',
            icon: <ExclamationCircleOutlined />,
            content: '确认删除？',
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {
                let { id, status } = item
                status = status === 1001 ? 1002 : 1001
                const res = await $api.user.delete({ id, status })
                if (res && res.success) {
                    message.success(res.message)
                    this.setState({ reset: true })
                    this.handlerFormSubmit({ ...this.state.pageData, status: '' }, true)
                    return
                }
                res && message.error(res.message)
            }
        })
    }
    componentDidMount () {
        this.setState({ loading: false, scroll : { y: window.innerHeight - 360 } })
        // 如果没有缓存，通过localStorage在本地缓存数据
        sessionStorage.setItem('users', JSON.stringify(this.props.data))
        window.addEventListener('resize', () => {
            this.setScroll()
        })
    }
    setScroll () {
        this.setState({ ...this.state, scroll : { y: window.innerHeight - 360 }  })
    }
    render () {
        const { ...state } = this.state
        return (
            <Fragment>
                <Head>
                    <title>会员列表</title>
                </Head>
                <AdvancedSearchForm
                title={'会员列表'}
                formItems={state.formItems}
                actions={
                    this.props.userinfo && this.props.userinfo.administrator && <Button className='float-right' onClick={() => Router.push('/user/add')} icon={<PlusOutlined />} type='primary'>创建会员</Button>
                }
                setParentState={this.handlerFormSubmit.bind(this)} state={this.state} />
                <Table
                    {...this.state}
                    scroll={state.scroll}
                    rowKey={(record) => record.id}
                    dataSource={state.hasData ? this.state.data : null}
                    columns={columns(this)}
                    onChange={(pageData) => this.handlerFormSubmit(pageData, true)}
                    pagination={{
                        ...this.state.pageData,
                        showSizeChanger: true,
                        showTitle: (total, range) => '页',
                        showTotal: (total, range) => `共 ${total} 条`
                    }}
                />
            </Fragment>
        )
    }
}
export default User